public class Solution114 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public void flatten(TreeNode root) {
        if (root==null){
            return;
        }
        dfs(root);
    }

    TreeNode[] dfs(TreeNode root){
        TreeNode start=root;
        TreeNode cur=root;
        TreeNode temp=root.right;
        if (root.left!=null){
            TreeNode[] t=dfs(root.left);
            cur.right=t[0];
            cur=t[1];
        }
        if (temp!=null){
            TreeNode[] t=dfs(temp);
            cur.right=t[0];
            cur=t[1];
        }
        start.left=null;
        return new TreeNode[]{start,cur};
    }

    public static void main(String[] args) {
        TreeNode treeNode=new TreeNode(1,new TreeNode(2,new TreeNode(3),new TreeNode(4)),new TreeNode(5,null,new TreeNode(6)));
        new Solution114().flatten(treeNode);
        System.out.println(treeNode.right.right.right.right.right.val);
    }
}
